using System;
using System.Collections.Generic;
using System.Text;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ipi.MCC
{
    public class MCCAjaxBaseControl : UserControl
    {

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            MCCAjaxBase.SetAjax(this.Page);
        }
    }
    
    public class MCCAjaxBaseWebPart : Microsoft.SharePoint.WebPartPages.WebPart
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            MCCAjaxBase.SetAjax(this.Page);
        }
    }
    
    class MCCAjaxBase
    {
/*        private static ScriptManager _AjaxManager;

        public static ScriptManager AjaxManager
        {
            get { return _AjaxManager; }
            set { _AjaxManager = value; }
        }*/

        public static void SetAjax(Page pgCurrent)
        {
            //get the existing ScriptManager if it exists on the page
            ScriptManager _AjaxManager = ScriptManager.GetCurrent(pgCurrent);

            if (_AjaxManager == null)
            {
                //create new ScriptManager and EnablePartialRendering
                _AjaxManager = new ScriptManager();
                _AjaxManager.EnablePartialRendering = true;

                // Fix problem with postbacks and form actions (DevDiv 55525)
                pgCurrent.ClientScript.RegisterStartupScript(typeof(MCCAjaxBase), pgCurrent.ID, "_spOriginalFormAction = document.forms[0].action;", true);

                //tag:"form" att:"onsubmit" val:"return _spFormOnSubmitWrapper()" blocks async postbacks after the first one
                //not calling "_spFormOnSubmitWrapper()" breaks all postbacks
                //returning true all the time, somewhat defeats the purpose of the _spFormOnSubmitWrapper() which is to block repetitive postbacks, but it allows MS AJAX Extensions to work properly
                //its a hack that hopefully has minimal effect
                if (pgCurrent.Form != null)
                {
                    string formOnSubmitAtt = pgCurrent.Form.Attributes["onsubmit"];
                    if (!string.IsNullOrEmpty(formOnSubmitAtt) && formOnSubmitAtt == "return _spFormOnSubmitWrapper();")
                    {
                        pgCurrent.Form.Attributes["onsubmit"] = "_spFormOnSubmitWrapper();";
                    }

                    //add the ScriptManager as the first control in the Page.Form
                    //I don't think this actually matters, but I did it to be consistent with how you are supposed to place the ScriptManager when used declaritevly
                    pgCurrent.Form.Controls.AddAt(0, _AjaxManager);
                }
            }
        }
    }
}
